# -*- coding:utf8 -*-
import pandas as pd
import requests,os
import json,time,re

APIKEY="fVkmSOXCgorPfvJ8Kl0ZKnIq"
secret_key="pOReWqziKfQXXMJ4WJDwbvwjnKtm6LKj"

def get_access_token():
    url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id="+APIKEY+"&client_secret="+secret_key
    print(url)   
    payload = json.dumps("")
    headers = {
        'Content-Type': 'application/json',
        'Accept': 'application/json'
    }
    response = requests.request("POST", url, headers=headers, data=payload)
    return response.json().get("access_token")

def main(contents,token):
    url = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/ernie-speed-128k?access_token=" + token
    payload = json.dumps({
        "messages": [
            {
                "role": "user",
                "content":'''Please determine which category the recipes corresponding to the following text belong to, including "Main Dishes", "Snacks", "Soups", "Salads", "Wheaten Food", "Breakfast", "Seafood", "Dessert", "Drinks", "Appetizers", "Side Dishes" and "Condiments". Only answer one or more categories such as "main dishes", "snacks", "soups", "salads", "wheaten food", "breakfast", "seafood", "dessert", "drinks", "appetizers", "side dishes" and "condiments", and do not answer any other words, separate multiple words with "|". The main text is:\n%s.'''%(contents)
            }
        ]
    })
    headers = {
        'Content-Type': 'application/json'
    }
    try:
        response = requests.request("POST", url, timeout=120, headers=headers, data=payload)
    except requests.exceptions.RequestException:
        return False
    result = json.loads(response.text)
    if 'result' not in result: return None
    return result['result']

if __name__ == '__main__':
    file = pd.read_excel("../allrecipes.xlsx")
    tmps  = [ candidate.split(',')[0] for candidate in open("tmp.txt","r") ]
    token = get_access_token()
    out = []
    for tmp in os.walk("../recipes"):
        for tfile in tmp[2]: 
            if tfile.split(".")[0].isdigit() == False: continue
            i = int(tfile.split('.')[0])
            if str(i)  in tmps: continue
            test_file = "../recipes/%d.md"%(i)
            if os.path.exists(test_file) == False: continue
            print(i)
            if i == 3046: name = 'Naan with Spinach and Feta'
            elif i == 51023: name = 'Chocolate Walnut Fudge'
            else: name = file.iloc[i]['菜名'].replace(",",".")
            if i == 3046: theme = 'wheaten food'
            elif i == 51023: theme = 'suger'
            else: theme = file.iloc[i]['分类'].replace(",",".")
            cate = main(open(test_file,"r").read().strip(),token)
            while cate is None:
                cate = main(open(test_file,"r").read().strip(),token)
            if '\n' in cate: cate = cate.split("\n")[0]
            if cate.count('"') in [2,4,6]: 
                matches = re.findall(r'"(.*?)"',cate)
                cate = "|".join([ str(match) for match in matches ])
            if cate.endswith("."): cate = cate.replace('.','')
            out.append("%d,%s,%s,%s"%(i,name,theme,cate))
            print(i,name,theme,cate)
            with open('tmp.txt','a') as f: f.write("%d,%s,%s,%s\n"%(i,name,theme,cate))
    with open("out.txt","w") as f: f.write("\n".join(out))
